﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Xeml.Document.Contracts;
using Xeml.Sampling.Contracts;
using Xeml.Document;
using ComponentFactory.Krypton.Toolkit;

namespace CompilerControls
{
    public partial class DataMappingCtrl : UserControl
    {
        IDocument _xemlDoc;
        DataProviderResource _provider;
        SampleMappings _mappings = new SampleMappings();

        public DataMappingCtrl()
        {
            InitializeComponent();
            sampleMappingBindingSource.DataSource = _mappings;
            fkmPanelCtrl1.KeyMapCtrl.KeyMapChanged += new EventHandler(KeyMapCtrl_KeyMapChanged);
        }

        void KeyMapCtrl_KeyMapChanged(object sender, EventArgs e)
        {
            if (kryptonDataGridView1.SelectedCells.Count > 0)
            {
                if (!_xemlDoc.ProviderDataMappings.ContainsKey(_provider.FriendlyName))
                {
                    _xemlDoc.ProviderDataMappings.Add(_provider.FriendlyName, new DataMappings());

                }

                object o = kryptonDataGridView1.Rows[kryptonDataGridView1.SelectedCells[0].RowIndex].Cells[3].Value;
                Type x = o.GetType();
                kryptonDataGridView1.Rows[kryptonDataGridView1.SelectedCells[0].RowIndex].Cells[3].Value = fkmPanelCtrl1.KeyMap;

                SampleMapping sm = kryptonDataGridView1.Rows[kryptonDataGridView1.SelectedCells[0].RowIndex].DataBoundItem as SampleMapping;

                if (!_xemlDoc.ProviderDataMappings[_provider.FriendlyName].Contains(sm.SampleId))
                {
                    _xemlDoc.ProviderDataMappings[_provider.FriendlyName].Add(sm.SidMapping);
                }
                sm.LookUp = _provider.Provider.Validate(sm.SidMapping);
                kryptonDataGridView1.Refresh();
            }
        }

        public void Setup(IDocument xemlDoc, DataProviderResource prov)
        {
            _xemlDoc = xemlDoc;
            _provider = prov;
            if (prov != null && prov.ComponentState == ComponentLoadState.Loaded)
            {
                ForeignKeyMap fkm = new ForeignKeyMap();
                foreach (var item in _provider.Provider.ListForeignKey())
                {
                    fkm.Add(item, "");
                }
                fkmPanelCtrl1.KeyMapCtrl.Setup(_provider);
                fkmPanelCtrl1.KeyMapCtrl.KeyMapProtoType = fkm;
            }

            sampleMappingBindingSource.DataSource = new List<SampleMapping>();

            if (_xemlDoc != null)
            {
                string provname = "";
                if (_provider != null)
                {
                    provname = prov.FriendlyName;

                    kryptonDataGridView1.Enabled = true;
                    buttonSpecAutoMap.Enabled = (_provider.ComponentState == ComponentLoadState.Loaded && _provider.Provider.SupportsAutoMapping) ? ButtonEnabled.True : ButtonEnabled.False;


                    var samples = (from sample in DocumentHelper.ExtractSamples(_xemlDoc)
                                   select
                                       sample);

                    List<SidMapping> sidmappings = new List<SidMapping>();
                    if (_xemlDoc.ProviderDataMappings.ContainsKey(_provider.FriendlyName))
                    {
                        sidmappings = (from sidmapping in _xemlDoc.ProviderDataMappings[_provider.FriendlyName]
                                       select
                                            sidmapping).ToList();
                    }

                    var sampleMap = (from sample in samples
                                     orderby sample.Id
                                     select
                                      new SampleMapping
                                      (
                                         new SidMapping(sample.Id)
                                      )).ToList();


                    foreach (SampleMapping sm in sampleMap)
                    {
                        SidMapping sid = sidmappings.FirstOrDefault(x => x.SampleId == sm.SampleId);
                        if (sid != null)
                        {
                            sm.SidMapping = sid;
                            sm.LookUp = _provider.Provider.Validate(sid);
                        }
                        sampleMappingBindingSource.Add(sm);
                    }

                }
                else
                {
                    kryptonDataGridView1.Enabled = false;
                    // kryptonButtonAutomap.Enabled = false;

                }
                kryptonDataGridView1.Refresh();
            }
        }

        private void kryptonButtonAutomap_Click(object sender, EventArgs e)
        {
            var sampleids = Xeml.Document.DocumentHelper.ExtractSamples(_xemlDoc).Select(x => x.Id).OrderBy(y => y);
            var sids = _provider.Provider.AutoMap(_xemlDoc.Id, _xemlDoc.Name, sampleids);
            if (sids.Count() > 0)
            {
                var mappings = from x in sids
                               select new SampleMapping
                                   {
                                       SidMapping = x,
                                       LookUp = _provider.Provider.Validate(x)
                                   };

                sampleMappingBindingSource.DataSource = mappings;
                sampleMappingBindingSource.ResetBindings(false);

                object o = sids.First().ForeignKeyMap;

                kryptonDataGridView1.Refresh();

                if (!_xemlDoc.ProviderDataMappings.ContainsKey(_provider.FriendlyName))
                    _xemlDoc.ProviderDataMappings.Add(_provider.FriendlyName, new DataMappings());
                _xemlDoc.ProviderDataMappings[_provider.FriendlyName].Clear();
                foreach (var sid in sids)
                {
                    //sid.ForeignKeyMap = "";
                    if (!_xemlDoc.ProviderDataMappings[_provider.FriendlyName].Contains(sid))
                        _xemlDoc.ProviderDataMappings[_provider.FriendlyName].Add(sid);
                }
            }
        }

        private void kryptonDataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                SidLookUpResult lp = (SidLookUpResult)kryptonDataGridView1.Rows[e.RowIndex].Cells[0].Value;
                switch (lp)
                {
                    case SidLookUpResult.UnknownSample:
                        goto default;
                    case SidLookUpResult.UnsupportedMapping:
                        {

                            e.Value = Properties.Resources.Error;
                            break;
                        }
                    case SidLookUpResult.Valid:
                        {
                            e.Value = Properties.Resources.OK;
                            break;
                        }
                    default:
                        {
                            e.Value = Properties.Resources.Unknown;
                            break;
                        }
                }
            }
        }

        private void kryptonDataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (kryptonDataGridView1.SelectedCells.Count > 0)
            {
                fkmPanelCtrl1.FkmTop = this.kryptonDataGridView1.GetCellDisplayRectangle(3, kryptonDataGridView1.SelectedCells[0].RowIndex, false).Top;

                fkmPanelCtrl1.KeyMap = (string)kryptonDataGridView1.Rows[kryptonDataGridView1.SelectedCells[0].RowIndex].Cells[3].Value;
            }
        }

        private void kryptonDataGridView1_Scroll(object sender, ScrollEventArgs e)
        {
            if (kryptonDataGridView1.SelectedCells.Count > 0)
            {
                fkmPanelCtrl1.FkmTop = this.kryptonDataGridView1.GetCellDisplayRectangle(3, kryptonDataGridView1.SelectedCells[0].RowIndex, false).Top;


            }
        }


    }
}
